{% extends 'base.html' %}
{% load static %}

{% block title %}浏览历史 - 城会玩{% endblock %}

{% block style %}
{{ block.super }}
<style>
/* 橙色主题样式 - 使用更具体的选择器和!important */
.container-fluid.bg-primary {
    background: linear-gradient(135deg, #FF6B35 0%, #FF8C5A 100%) !important;
}

.bg-primary {
    background-color: #FF6B35 !important;
}

.text-primary {
    color: #FF6B35 !important;
}

.btn-primary {
    background-color: #FF6B35 !important;
    border-color: #FF6B35 !important;
}

.btn-primary:hover {
    background-color: #e55a2b !important;
    border-color: #e55a2b !important;
    transform: translateY(-2px);
}

.btn-outline-primary {
    color: #FF6B35 !important;
    border-color: #FF6B35 !important;
}

.btn-outline-primary:hover {
    background-color: #FF6B35 !important;
    border-color: #FF6B35 !important;
    color: white !important;
}

/* 主页样式统一 */
.activity-card {
    transition: all 0.3s ease;
    border-radius: 12px;
    overflow: hidden;
}

.activity-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(255, 107, 53, 0.15) !important;
}

.hover-shadow:hover {
    box-shadow: 0 8px 25px rgba(255, 107, 53, 0.15) !important;
}

.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.empty-state {
    max-width: 400px;
    margin: 0 auto;
}

/* 卡片悬停效果 */
.card {
    border-radius: 12px;
}

.badge {
    font-weight: 500;
    padding: 0.5em 0.75em;
}

/* 分页样式 */
.page-item.active .page-link {
    background-color: #FF6B35 !important;
    border-color: #FF6B35 !important;
}

.page-link {
    color: #FF6B35 !important;
}

.page-link:hover {
    background-color: #FF6B35 !important;
    border-color: #FF6B35 !important;
    color: white !important;
}

/* 图标颜色修正 */
.fas.fa-map-marker-alt.text-danger,
.far.fa-calendar.text-info {
    color: #FF6B35 !important;
}

/* 确保文字在橙色背景上可见 */
.bg-primary.text-white,
.bg-primary .text-white {
    color: white !important;
}

/* 徽章背景色 */
.badge.bg-primary {
    background-color: #FF6B35 !important;
}
</style>
{% endblock %}

{% block content %}
<!-- 页面头部 -->
<div class="container-fluid bg-primary text-white py-4 mb-4">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="h2 mb-2">
                    <i class="fas fa-history me-3"></i>浏览历史
                </h1>
                <p class="mb-0 opacity-75">查看您最近浏览过的精彩活动</p>
            </div>
            <div class="col-md-4 text-md-end">
                <a href="/meet/index/" class="btn btn-light btn-lg">
                    <i class="fas fa-home me-2"></i>返回首页
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div class="row">
        <div class="col-12">
            <!-- 统计信息和操作栏 -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-chart-bar text-primary fs-4 me-3"></i>
                                <div>
                                    <h5 class="mb-1">浏览统计</h5>
                                    <p class="text-muted mb-0">共 <span class="fw-bold text-primary">{{ total_count }}</span> 条浏览记录</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 text-md-end">
                            {% if page_obj %}
                            <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#clearAllModal">
                                <i class="fas fa-trash-alt me-2"></i>清空所有历史
                            </button>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 浏览历史列表 -->
            {% if page_obj %}
                <div class="row g-4">
                    {% for history in page_obj %}
                    <div class="col-xl-3 col-lg-4 col-md-6">
                        <div class="card activity-card h-100 border-0 shadow-sm hover-shadow">
                            <div class="position-relative">
                                <img src="{{ history.activity.image.url }}"
                                     class="card-img-top"
                                     alt="{{ history.activity.title }}"
                                     style="height: 200px; object-fit: cover;">
                                <div class="card-img-overlay d-flex justify-content-between align-items-start p-3">
                                    <span class="badge bg-primary bg-opacity-90">{{ history.activity.category.name }}</span>
                                    <span class="badge bg-dark bg-opacity-75">
                                        <i class="far fa-clock me-1"></i>
                                        {{ history.viewed_at|date:"m-d H:i" }}
                                    </span>
                                </div>
                            </div>

                            <div class="card-body d-flex flex-column">
                                <h6 class="card-title fw-bold text-dark mb-2 line-clamp-2" style="min-height: 3rem;">
                                    {{ history.activity.title }}
                                </h6>

                                <div class="mb-3">
                                    <p class="text-muted small mb-2">
                                        <i class="fas fa-map-marker-alt text-danger me-1"></i>
                                        {{ history.activity.location_name }}
                                    </p>
                                    {% if history.activity.start_time %}
                                    <p class="text-muted small mb-2">
                                        <i class="far fa-calendar text-info me-1"></i>
                                        {{ history.activity.start_time|date:"Y-m-d H:i" }}
                                    </p>
                                    {% endif %}
                                </div>

                                <div class="mt-auto">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span class="text-warning fw-bold">
                                            <i class="fas fa-users me-1"></i>
                                            {{ history.activity.current_participants }}/{{ history.activity.max_participants }}
                                        </span>
                                        {% if history.activity.is_full %}
                                        <span class="badge bg-danger">已满员</span>
                                        {% else %}
                                        <span class="badge bg-success">可报名</span>
                                        {% endif %}
                                    </div>

                                    <div class="d-grid gap-2">
                                        <a href="/meet/active_detail/{{ history.activity.id }}/"
                                           class="btn btn-outline-primary btn-sm">
                                            <i class="fas fa-eye me-1"></i>查看详情
                                        </a>
                                        <button class="btn btn-outline-danger btn-sm delete-single"
                                                data-history-id="{{ history.id }}"
                                                data-activity-title="{{ history.activity.title }}">
                                            <i class="fas fa-trash me-1"></i>删除记录
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>

                <!-- 分页 -->
                {% if page_obj.has_other_pages %}
                <div class="mt-5">
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            {% if page_obj.has_previous %}
                                <li class="page-item">
                                    <a class="page-link" href="?page=1" aria-label="First">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
                                        <i class="fas fa-angle-left"></i>
                                    </a>
                                </li>
                            {% endif %}

                            {% for num in page_obj.paginator.page_range %}
                                {% if page_obj.number == num %}
                                    <li class="page-item active">
                                        <span class="page-link">{{ num }}</span>
                                    </li>
                                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                    <li class="page-item">
                                        <a class="page-link" href="?page={{ num }}">{{ num }}</a>
                                    </li>
                                {% endif %}
                            {% endfor %}

                            {% if page_obj.has_next %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Next">
                                        <i class="fas fa-angle-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}" aria-label="Last">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            {% endif %}
                        </ul>
                    </nav>
                    <p class="text-center text-muted mt-2">
                        第 {{ page_obj.number }} 页，共 {{ page_obj.paginator.num_pages }} 页
                    </p>
                </div>
                {% endif %}

            {% else %}
                <!-- 空状态 -->
                <div class="text-center py-5 my-5">
                    <div class="empty-state">
                        <i class="fas fa-history fa-4x text-primary mb-4"></i>
                        <h3 class="text-muted mb-3">暂无浏览历史</h3>
                        <p class="text-muted mb-4">您还没有浏览过任何活动，快去发现精彩活动吧！</p>
                        <div class="d-flex justify-content-center gap-3">
                            <a href="/meet/index/" class="btn btn-primary btn-lg">
                                <i class="fas fa-home me-2"></i>返回首页
                            </a>
                            <a href="/meet/active/" class="btn btn-outline-primary btn-lg">
                                <i class="fas fa-search me-2"></i>发现活动
                            </a>
                        </div>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 清空所有确认模态框 -->
<div class="modal fade" id="clearAllModal" tabindex="-1" aria-labelledby="clearAllModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0">
                <h5 class="modal-title text-danger" id="clearAllModalLabel">
                    <i class="fas fa-exclamation-triangle me-2"></i>确认清空
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body py-4">
                <div class="text-center">
                    <i class="fas fa-trash-alt fa-3x text-danger mb-3"></i>
                    <h5 class="fw-bold mb-3">确定要清空所有浏览历史吗？</h5>
                    <p class="text-muted">此操作将删除所有浏览记录，且不可恢复。</p>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-2"></i>取消
                </button>
                <button type="button" class="btn btn-danger" id="confirmClearAll">
                    <i class="fas fa-check me-2"></i>确认清空
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成 - 浏览历史页面');

    // 删除单个浏览记录
    document.querySelectorAll('.delete-single').forEach(button => {
        button.addEventListener('click', function() {
            console.log('删除按钮被点击');
            const historyId = this.getAttribute('data-history-id');
            const activityTitle = this.getAttribute('data-activity-title');
            console.log('ID:', historyId, '标题:', activityTitle);

            if (confirm(`确定要删除"${activityTitle}"的浏览记录吗？`)) {
                // 发送AJAX请求
                fetch(`/meet/delete_browsing_history/${historyId}/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': getCookie('csrftoken'),
                        'X-Requested-With': 'XMLHttpRequest',
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('删除成功！');
                        // 刷新页面
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                    alert('网络错误，请重试');
                });
            }
        });
    });

    // 清空所有浏览记录
    const clearAllBtn = document.getElementById('confirmClearAll');
    if (clearAllBtn) {
        clearAllBtn.addEventListener('click', function() {
            console.log('清空所有按钮被点击');

            const originalText = this.innerHTML;
            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>清空中...';

            fetch('/meet/delete_browsing_history/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('清空成功！');
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('clearAllModal'));
                    if (modal) {
                        modal.hide();
                    }
                    // 刷新页面
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    alert('清空失败: ' + data.message);
                    this.disabled = false;
                    this.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('网络错误，请重试');
                this.disabled = false;
                this.innerHTML = originalText;
            });
        });
    }

    // 获取CSRF token的函数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 卡片悬停效果
    document.querySelectorAll('.activity-card').forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.classList.add('hover-shadow');
        });
        card.addEventListener('mouseleave', function() {
            this.classList.remove('hover-shadow');
        });
    });
});
</script>
{% endblock %}